package com.s3u4.demo.zookeeper.base;

import com.google.gson.Gson;
import com.s3u4.demo.zookeeper.JSON;
import com.s3u4.demo.zookeeper.ZkConfig;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

/**
 * Created by Captain on 30/11/2017.
 */
public class ZookeeperClient {

    public static volatile int index = 0;

    public static ZooKeeper client;

    public static String path = "/persistent_sequential";

    private static class MyWatcher implements Watcher {
        @Override
        public void process(WatchedEvent event) {
            index++;
            System.out.println("WatchedEvent : status --> " + event.getState() + "  index : " + index);
            try {
                byte[] data = client.getData(path,true,null);

                System.out.println("data : " + new String(data));
                Stat stat = client.exists(path,null);
                if ( stat != null ){
                    System.out.println(new Gson().toJson(stat));
                }

                List<String> children = client.getChildren(path,this);
                JSON.toJson(children);


            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            Watcher watcher = new MyWatcher();
            client = new ZooKeeper(ZkConfig.ZK_HOST,ZkConfig.SESSION_TIMECOUNT,watcher);

            Stat stat = client.exists(path,true);
            if ( stat == null ){
                System.out.println("Create node : " + path);
                client.create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            }

            client.getChildren(path,true);


            while (true){

            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }

}
